package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.exception.BusinessException;
import com.example.entity.emp.SysRole;
import com.example.entity.emp.SysRolePermission;
import com.example.entity.emp.SysUserRole;
import com.example.mapper.emp.SysRoleMapper;
import com.example.service.SysRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色服务实现类
 */
@Service
@RequiredArgsConstructor
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Override
    public Page<SysRole> page(Integer current, Integer size, String roleName) {
        Page<SysRole> page = new Page<>(current, size);
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        
        if (roleName != null && !roleName.isEmpty()) {
            wrapper.like(SysRole::getRoleName, roleName);
        }
        
        wrapper.orderByAsc(SysRole::getId);
        return page(page, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SysRole role) {
        // 检查角色名和角色编码是否重复
        checkRoleNameAndCode(role);
        
        // 设置创建时间和状态
        role.setStatus(1);
        role.setCreatedTime(LocalDateTime.now());
        
        save(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysRole role) {
        // 检查角色名和角色编码是否重复
        checkRoleNameAndCode(role);
        
        // 设置更新时间
        role.setUpdatedTime(LocalDateTime.now());
        
        updateById(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        // 检查角色是否已分配给用户
        long userCount = baseMapper.countUserByRoleId(id);
        if (userCount > 0) {
            throw new BusinessException("角色已分配给用户，无法删除");
        }
        
        // 删除角色权限关联
        baseMapper.deleteRolePermissionByRoleId(id);
        
        // 删除角色
        removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignPermissions(Long roleId, List<Long> permissionIds) {
        // 删除原有角色权限关联
        baseMapper.deleteRolePermissionByRoleId(roleId);
        
        if (permissionIds != null && !permissionIds.isEmpty()) {
            // 构建角色权限关联
            List<SysRolePermission> rolePermissions = new ArrayList<>();
            LocalDateTime now = LocalDateTime.now();
            
            for (Long permissionId : permissionIds) {
                SysRolePermission rolePermission = new SysRolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(permissionId);
                rolePermission.setCreatedTime(now);
                rolePermissions.add(rolePermission);
            }
            
            // 批量插入角色权限关联
            baseMapper.insertRolePermissionBatch(rolePermissions);
        }
    }

    @Override
    public List<Long> getUserRoleIds(Long userId) {
        return baseMapper.selectUserRoleIds(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignUserRoles(Long userId, List<Long> roleIds) {
        // 删除原有用户角色关联
        baseMapper.deleteUserRoleByUserId(userId);
        
        if (roleIds != null && !roleIds.isEmpty()) {
            // 构建用户角色关联
            List<SysUserRole> userRoles = new ArrayList<>();
            LocalDateTime now = LocalDateTime.now();
            
            for (Long roleId : roleIds) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRole.setCreatedTime(now);
                userRoles.add(userRole);
            }
            
            // 批量插入用户角色关联
            baseMapper.insertUserRoleBatch(userRoles);
        }
    }
    
    /**
     * 检查角色名和角色编码是否重复
     */
    private void checkRoleNameAndCode(SysRole role) {
        // 构建查询条件，需要考虑更新时不能与其他角色重复
        LambdaQueryWrapper<SysRole> wrapper = new LambdaQueryWrapper<>();
        
        // 检查角色名是否重复
        wrapper.eq(SysRole::getRoleName, role.getRoleName());
        if (role.getId() != null) {
            wrapper.ne(SysRole::getId, role.getId());
        }
        
        long count = count(wrapper);
        if (count > 0) {
            throw new BusinessException("角色名已存在");
        }
        
        // 检查角色编码是否重复
        wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRole::getRoleCode, role.getRoleCode());
        if (role.getId() != null) {
            wrapper.ne(SysRole::getId, role.getId());
        }
        
        count = count(wrapper);
        if (count > 0) {
            throw new BusinessException("角色编码已存在");
        }
    }
} 